package hwr.iamdr.Service;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;

import com.google.appengine.api.datastore.*;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.gson.stream.JsonWriter;

@SuppressWarnings("serial")
public class RegisterServlet extends HttpServlet
{
	static final DatastoreService dataStore	= DatastoreServiceFactory.getDatastoreService();
	static final Logger logger	= Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);

	void SendMail(Key key,InternetAddress adminAddr,InternetAddress emailAddr,HttpServletRequest req,HttpServletResponse resp) throws IOException
	{
		try
		{
			Session session = Session.getDefaultInstance(new Properties());

			MimeMessage msg = new MimeMessage(session);
			msg.setFrom(adminAddr);

			msg.addRecipient(MimeMessage.RecipientType.TO,emailAddr);
			msg.setSubject("Activation for your IAmDr account");
			msg.setText("Thank You for sending request to our service\n\n" +
					"Please click the link below (or paste & go on your browser) to activate your account\n" +
					"http://" + req.getServerName() + "/activation?key=" + KeyFactory.keyToString(key));

			Transport.send(msg);
		}
		catch (Exception e)
		{
			logger.log(Level.SEVERE,e.toString());
			resp.getWriter().print(e.toString());
			resp.setStatus(0);
			return;
		}

		JsonWriter writer	= new JsonWriter(resp.getWriter());
		writer.beginObject();
		writer.name("code");
		writer.value(1);
		writer.endObject();
		writer.close();

	}

	@Override
	protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
	{
		String email	= req.getParameter("email");
		String password	= req.getParameter("password");

		InternetAddress emailAddr;
		InternetAddress adminAddr;
		try
		{
			adminAddr	= new InternetAddress("dr.kanapon@gmail.com","IAmDr Admin");
			emailAddr	= new InternetAddress(email);
		}
		catch (AddressException e)
		{
			resp.getWriter().print("Invalid EMail " + email);
			resp.setStatus(0);

			logger.log(Level.WARNING,"EMail : " + email);
			logger.log(Level.SEVERE,e.toString());
			return;
		}

		if(password == null || password.length() < 6)
		{
			Query query	= new Query("Member");
			query.addFilter("email",FilterOperator.EQUAL,email);
			Entity entity	= dataStore.prepare(query).asSingleEntity();
			if(entity == null)
			{
				resp.getWriter().print("EMail " + email + " Not registered yet");
				resp.setStatus(0);
				return;
			}

			SendMail(entity.getKey(),adminAddr,emailAddr,req,resp);
		}
		else
		{
			Query query	= new Query("Member");
			query.addFilter("email",FilterOperator.EQUAL,email);
			if(dataStore.prepare(query).countEntities(FetchOptions.Builder.withLimit(1)) > 0)
			{
				logger.log(Level.WARNING,"EMail " + email + " was Duplicate");

				resp.getWriter().print("Duplicate EMail " + email);
				return;
			}

			Entity entity	= new Entity("Member");
			entity.setProperty("email",email);
			entity.setProperty("password",password);
			entity.setProperty("activated",false);
			Key key	= dataStore.put(entity);

			SendMail(key,adminAddr,emailAddr,req,resp);
		}
	}
}
